import cssModule from "@/views/system/user/userCenter.module.scss";
import { Tabs, Form, Input, Avatar, Button, message } from "antd";
import React, { useState, useEffect } from "react";
import { UserForm } from "@/types";
import { UserOutlined } from "@ant-design/icons";
import ImageClip from "@/components/ImageClip";
import { uploadFile } from "@/api";
import {
    getUserById,
    changeUserInfo,
    changePassword,
} from "../../../api/user/index";
import { useMySelector } from "../../../redux/hook";
const TabPane = Tabs.TabPane;
const UserCenter: React.FC = () => {
    const [userForm, setUserForm] = useState({} as UserForm);
    const [visible, setVisible] = useState(false);
    const userInfo = useMySelector(state => state.user.userInfo);
    const [form] = Form.useForm();
    const [changePasswordForm, setChangePasswordForm] = useState({
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
    });
    const fileUpload = (blob: Blob, fileName: string) => {
        uploadFile(blob, fileName).then(res => {
            setUserForm({ ...userForm, avatar: res.data.path });
            setVisible(false);
        });
    };
    let flag = false;
    const submit = async () => {
        await form.validateFields();
        if (flag) {
            return;
        }
        flag = true;
        try {
            await changeUserInfo(userForm);
            message.success("更新成功");
        } finally {
            setTimeout(() => {
                flag = false;
            }, 1000);
        }
    };
    const changePasswordSubmit = async () => {
        if (flag) {
            return;
        }
        flag = true;
        try {
            await changePassword(changePasswordForm);
            message.success("修改成功");
        } finally {
            setTimeout(() => {
                flag = false;
            }, 1000);
        }
    };
    useEffect(() => {
        userInfo &&
            getUserById(userInfo?.id!).then(res => {
                const user = res.data;
                const userFormNew = {
                    id: user.id,
                    username: user.username,
                    phone: user.phone,
                    nickname: user.nickname,
                    avatar: user.avatar,
                };
                setUserForm(userFormNew);
                form.setFieldsValue(userFormNew);
            });
    }, [userInfo]);
    return (
        <div>
            <Tabs defaultActiveKey="1" type="card">
                <TabPane tab="用户信息" key="1">
                    <div className={cssModule.userInfoWrap}>
                        <Form form={form} labelCol={{ span: 4 }}>
                            <Form.Item
                                name="username"
                                label="用户名"
                                key="username"
                                rules={[
                                    { required: true, message: "请填写用户名" },
                                ]}
                            >
                                <Input
                                    value={userForm.username}
                                    onChange={e =>
                                        setUserForm({
                                            ...userForm,
                                            username: e.target.value,
                                        })
                                    }
                                ></Input>
                            </Form.Item>
                            <Form.Item
                                name="nickname"
                                label="用户名称"
                                key="nickname"
                                rules={[
                                    {
                                        required: true,
                                        message: "请填写用户名称",
                                    },
                                ]}
                            >
                                <Input
                                    value={userForm.nickname}
                                    onChange={e =>
                                        setUserForm({
                                            ...userForm,
                                            nickname: e.target.value,
                                        })
                                    }
                                ></Input>
                            </Form.Item>
                            <Form.Item
                                name="phone"
                                label="手机号"
                                key="phone"
                                rules={[
                                    { required: true, message: "请填写手机号" },
                                ]}
                            >
                                <Input
                                    value={userForm.phone}
                                    onChange={e =>
                                        setUserForm({
                                            ...userForm,
                                            phone: e.target.value,
                                        })
                                    }
                                ></Input>
                            </Form.Item>
                            <Form.Item label="头像">
                                <div onClick={() => setVisible(true)}>
                                    <Avatar
                                        size={50}
                                        src={userForm.avatar}
                                        icon={<UserOutlined />}
                                    />
                                </div>
                            </Form.Item>
                            <Form.Item>
                                <Button type="primary" block onClick={submit}>
                                    提交
                                </Button>
                            </Form.Item>
                        </Form>
                    </div>
                </TabPane>
                <TabPane tab="修改密码" key="2">
                    <div className={cssModule.changePasswordWrap}>
                        <Form
                            labelCol={{ span: 5 }}
                            onFinish={() => {
                                changePasswordSubmit();
                            }}
                        >
                            <Form.Item
                                label="旧密码"
                                name="oldPassword"
                                rules={[
                                    { required: true, message: "请填写旧密码" },
                                ]}
                            >
                                <Input
                                    value={changePasswordForm.oldPassword}
                                    type="password"
                                    onChange={e =>
                                        setChangePasswordForm({
                                            ...changePasswordForm,
                                            oldPassword: e.target.value,
                                        })
                                    }
                                ></Input>
                            </Form.Item>
                            <Form.Item
                                name="newPassword"
                                label="新密码"
                                rules={[
                                    { required: true, message: "请填写新密码" },
                                    { max: 10, message: "新密码不能超过10位" },
                                ]}
                            >
                                <Input
                                    value={changePasswordForm.newPassword}
                                    type="password"
                                    onChange={e =>
                                        setChangePasswordForm({
                                            ...changePasswordForm,
                                            newPassword: e.target.value,
                                        })
                                    }
                                ></Input>
                            </Form.Item>
                            <Form.Item
                                name="confirmPassword"
                                label="再次确认密码"
                                required
                                rules={[
                                    {
                                        validator: async (
                                            _,
                                            confirmPassword
                                        ) => {
                                            if (!confirmPassword) {
                                                return Promise.reject(
                                                    "请填写再次确认密码"
                                                );
                                            }
                                            if (
                                                confirmPassword !==
                                                changePasswordForm.confirmPassword
                                            ) {
                                                return Promise.reject(
                                                    new Error(
                                                        "两次输入密码不一致"
                                                    )
                                                );
                                            }
                                        },
                                    },
                                ]}
                            >
                                <Input
                                    value={changePasswordForm.confirmPassword}
                                    type="password"
                                    onChange={e =>
                                        setChangePasswordForm({
                                            ...changePasswordForm,
                                            confirmPassword: e.target.value,
                                        })
                                    }
                                ></Input>
                            </Form.Item>
                            <Form.Item>
                                <Button type="primary" block htmlType="submit">
                                    提交
                                </Button>
                            </Form.Item>
                        </Form>
                    </div>
                </TabPane>
            </Tabs>
            <ImageClip
                visible={visible}
                onCancel={() => setVisible(false)}
                onOk={fileUpload}
            ></ImageClip>
        </div>
    );
};
export default UserCenter;
